package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.common.exception.RecoupException;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.tenant.TenantContextHolder;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.system.dao.TenantMapper;
import com.qinglei.recoup.system.dao.VitalSignsAlarmMapper;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.*;
import com.qinglei.recoup.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author syp
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Resource
    private SystemConfigService systemConfigService;

    @Autowired
    private RadarService radarService;

    @Autowired
    private UserService userService;

    @Autowired
    private VitalSignsAlarmService vitalSignsAlarmService;

    @Autowired
    private RealTimeMonitoringService realTimeMonitoringService;

    @Resource
    private RedisService redisService;


    @Autowired
    private HealthBigDataService healthBigDataService;

    @Value("${recoup.tenant.theme.default-banner-url}")
    private String defaultBannerUrl;

    @Value("${recoup.tenant.theme.default-banner-color}")
    private String defaultBannerColor;

    @Value("${recoup.tenant.default-system-configs}")
    private String defaultSystemConfigs;

    @Value("${recoup.tenant.default-vital-signs-alarm}")
    private String defaultVitalSignsAlarm;

    @Value("${recoup.tenant.default-real-time-monitoring}")
    private String defaultRealTimeMonitoring;

    @Value("${recoup.tenant.default-health-big-data}")
    private String defaultHealthBigData;

    @Autowired
    private MonitorTimeService monitorTimeService;

    @Autowired
    private BuildingService buildingService;

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public boolean add(AddTenantParam param) throws RecoupException, RedisConnectException {
        Tenant tenant = new Tenant();
        tenant.setName(param.getName());
        tenant.setSiteUrl(param.getSiteUrl());
        TenantThemeBO tenantThemeBO = new TenantThemeBO(defaultBannerUrl, defaultBannerColor);
        tenant.setTheme(JsonUtils.objectToJson(tenantThemeBO));
        boolean res = this.save(tenant);
        if (!res) {
            throw new RecoupException("保存机构失败");
        }
        // 添加默认系统配置
        if (StringUtils.isNotEmpty(defaultSystemConfigs)) {
            List<SystemConfig> systemConfigs = JsonUtils.jsonToList(defaultSystemConfigs, SystemConfig.class);
            if (CollectionUtils.isNotEmpty(systemConfigs)) {
                for (SystemConfig systemConfig : systemConfigs) {
                    systemConfig.setTenantId(tenant.getId());
                }
                res = systemConfigService.saveBatch(systemConfigs);
                if (!res) {
                    throw new RecoupException("保存系统设置失败");
                }
                // 重新载入接单超时时间到缓存
                try {
                    systemConfigService.loadTakeEventTimeoutRedisCache();
                } catch (RedisConnectException e) {
                    log.error("添加机构后 载入接单超时缓存错误", e);
                }
            }
        }
        //添加初始化生命体征报警阈值默认值
        List<VitalSignsAlarm>  vitalSignsAlarmList =JsonUtils.jsonToList(defaultVitalSignsAlarm, VitalSignsAlarm.class);
        vitalSignsAlarmList.forEach(f->f.setTenantId(tenant.getId()));
        vitalSignsAlarmService.saveBatch(vitalSignsAlarmList);

        vitalSignsAlarmList.forEach(t->{
            if(t.getSignType()==1 && t.getEnable()==1){
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("tenant_id",t.getTenantId());
                List<Building> buildings =   buildingService.getBaseMapper().selectList(queryWrapper);
                buildings.forEach(s->{
                    UpdateOutBedTimeoutParam param1 = new UpdateOutBedTimeoutParam();
                    param1.setObjId("b"+s.getId());
                    param1.setType(4);
                    param1.setOutBedTimeout(LocalTime.of(0,0, Integer.parseInt(t.getContinued())).toString());
                    monitorTimeService.updateOutBedTimeout(param1);
                });
            }
        });

        List<VitalSignsAlarm> VitalSignsAlarmList2 = vitalSignsAlarmService.list(Wrappers.<VitalSignsAlarm>lambdaQuery().eq(VitalSignsAlarm::getTenantId, tenant.getId()));
        VitalSignsAlarmList2.forEach(f->{
            f.setCreateTime(null);
            f.setModifyTime(null);
            String s = JsonUtils.objectToJson(f);
            try {
                redisService.set("VitalSignsAlarm-"+f.getTenantId()+"-"+f.getSignType(),s);
            } catch (RedisConnectException e) {
                e.printStackTrace();
            }

        });

        //添加初始化实时监测默认值
        List<RealTimeMonitoring>  realTimeMonitoringList =JsonUtils.jsonToList(defaultRealTimeMonitoring, RealTimeMonitoring.class);
        realTimeMonitoringList.forEach(f->f.setTenantId(tenant.getId()));
        realTimeMonitoringService.saveBatch(realTimeMonitoringList);
        List<RealTimeMonitoring> RealTimeMonitoringList2 = realTimeMonitoringService.list(Wrappers.<RealTimeMonitoring>lambdaQuery().eq(RealTimeMonitoring::getTenantId, tenant.getId()));
        RealTimeMonitoringList2.forEach(f->{
            f.setCreateTime(null);
            f.setModifyTime(null);
        });
        String s1 = JsonUtils.objectToJson(RealTimeMonitoringList2);
        redisService.set("RealTimeMonitoring-"+RealTimeMonitoringList2.get(0).getTenantId(),s1);

        //添加初始化健康大数据阈值默认值
        List<HealthBigData>  healthBigDataList =JsonUtils.jsonToList(defaultHealthBigData, HealthBigData.class);
        healthBigDataList.forEach(f->f.setTenantId(tenant.getId()));
        healthBigDataService.saveBatch(healthBigDataList);
        List<HealthBigData> HealthBigDataList2 = healthBigDataService.list(Wrappers.<HealthBigData>lambdaQuery().eq(HealthBigData::getTenantId, tenant.getId()));
        HealthBigDataList2.forEach(f->{
            String s = JsonUtils.objectToJson(f);
            try {
                redisService.set("HealthBigData-"+f.getTenantId()+"-"+f.getBigDataType(),s);
            } catch (RedisConnectException e) {
                e.printStackTrace();
            }

        });
        return true;
    }

    @Override
    public IPage<TenantDetailVO> getPageList(TenantSearchParam searchParam, PageParam pageParam) {
        Page<Tenant> page = new Page<>();
        page.setCurrent(pageParam.getPageNum());
        page.setSize(pageParam.getPageSize());
        IPage<TenantDetailBO> tenantPage = this.baseMapper.pageTenant(page, searchParam);
        List<TenantDetailBO> tenantList = tenantPage.getRecords();
        List<TenantDetailVO> tenantDetailVOList = new ArrayList<>();
        for (TenantDetailBO tenant : tenantList) {
            TenantDetailVO tenantDetailVO = new TenantDetailVO();
            BeanUtils.copyProperties(tenant, tenantDetailVO);
            // 组装管理员信息
            if (tenant.getAdminUserId() != 0) {
                UserDetailVO userDetailVO = new UserDetailVO();
                userDetailVO.setUserId(tenant.getAdminUserId());
                userDetailVO.setName(tenant.getAdminName());
                userDetailVO.setMobile(tenant.getAdminMobile());
                tenantDetailVO.setAdminUser(userDetailVO);
            }
            // 组装主题信息
            if (StringUtils.isNotEmpty(tenant.getTheme())) {
                TenantThemeBO tenantThemeBO = JsonUtils.jsonToBean(tenant.getTheme(), TenantThemeBO.class);
                tenantDetailVO.setTheme(tenantThemeBO);
            }
            // 查询机构统计数据
            TenantContextHolder.setTenantId(tenant.getId());
            TenantAssetVO tenantAssetInfo = this.getTenantAssetInfo();
            BeanUtils.copyProperties(tenantAssetInfo, tenantDetailVO);
            TenantContextHolder.clear();
            tenantDetailVOList.add(tenantDetailVO);
        }

        Page<TenantDetailVO> tenantDetailVOPage = new Page<>();
        tenantDetailVOPage.setTotal(tenantPage.getTotal());
        tenantDetailVOPage.setSize(tenantPage.getSize());
        tenantDetailVOPage.setCurrent(tenantPage.getCurrent());
        tenantDetailVOPage.setRecords(tenantDetailVOList);
        return tenantDetailVOPage;
    }

    @Override
    public TenantAssetVO getTenantAssetInfo() {
        TenantAssetVO tenantAssetVO = new TenantAssetVO();
        // 查询机构雷达统计信息
        RadarStatisticsBO radarStatisticsBO = radarService.selectRadarStatistics();
        if (radarStatisticsBO != null && radarStatisticsBO.getDeviceCnt() != 0) {
            tenantAssetVO.setDeviceCnt(radarStatisticsBO.getDeviceCnt().toString());
            tenantAssetVO.setBoundCnt(radarStatisticsBO.getBoundCnt().toString());
            tenantAssetVO.setWorkingCnt(radarStatisticsBO.getWorkingCnt().toString());
            tenantAssetVO.setOfflineCnt(radarStatisticsBO.getOfflineCnt().toString());
        }
        int userCnt = userService.count();
        if (userCnt != 0) {
            tenantAssetVO.setUserCnt(String.valueOf(userCnt));
        }
        return tenantAssetVO;
    }
}
